// 导入发送邮件的模块
const nodemailer = require('nodemailer');
const config = require('./index');

// 邮箱服务商配置
const MAIL_CONFIGS = {
    qq: {
        host: "smtp.qq.com",
        port: 465,
        secure: true
    },
    163: {
        host: "smtp.163.com",
        port: 465,
        secure: true
    }
    // 可以添加更多配置...
};

class EmailSender {
    constructor() {
        this.transporters = {};
        this.initTransporters();
    }

    // 初始化所有配置的邮箱传输器
    initTransporters() {
        Object.entries(config.mailAccounts).forEach(([type, account]) => {
            const mailConfig = MAIL_CONFIGS[type];
            if (mailConfig && account.email && account.pass) {
                this.transporters[type] = nodemailer.createTransport({
                    host: mailConfig.host,
                    port: mailConfig.port,
                    secure: mailConfig.secure,
                    auth: {
                        user: account.email,
                        pass: account.pass
                    }
                });
            }
        });
    }

    // 生成验证码
    generateVerifyCode(length = 6) {
        return Math.random().toString().slice(-length);
    }

    // 发送邮件
    async sendMail(options) {
        const { to, subject, html, from = config.defaultMailType } = options;

        if (!this.transporters[from]) {
            throw new Error(`未配置的邮箱类型: ${from}`);
        }

        try {
            const transporter = this.transporters[from];
            const account = config.mailAccounts[from];
            
            const info = await transporter.sendMail({
                from: `"${config.projectName}" <${account.email}>`,
                to,
                subject,
                html
            });

            return {
                success: true,
                messageId: info.messageId,
                type: from
            };
        } catch (error) {
            console.error('发送邮件失败:', error);
            return {
                success: false,
                error: error.message,
                type: from
            };
        }
    }

    // 发送验证码
    async sendVerifyCode(to, type = config.defaultMailType, projectName = config.projectName) {
        const code = this.generateVerifyCode();
        const subject = `${projectName}---邮箱验证码`;
        const html = `
            <div style="padding: 20px; background-color: #f5f5f5;">
                <h1>您好：</h1>
                <p style="font-size: 18px;color:#000;">
                    您的验证码为：
                    <span style="font-size: 16px;color:#f00;"><b>${code}</b></span>
                </p>
                <p>您当前正在${projectName}验证账号，验证码告知他人将会导致数据信息被盗，请勿泄露!</p>
                <p style="font-size: 1.5rem;color:#999;">60秒内有效</p>
            </div>
        `;

        const result = await this.sendMail({
            to,
            subject,
            html,
            from: type
        });

        return {
            ...result,
            code: result.success ? code : null
        };
    }
}

module.exports = new EmailSender();
